using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using I2.Loc;
using Prime31;
using Rilisoft.MiniJson;
using UnityEngine;
using UnityEngine.SceneManagement;

public class InAppSubscriptionsController : MonoBehaviour
{
	public class InAppPromo
	{
		private bool enabled;

		public GamerType gamerType;

		public int hoboTime;

		public string subscriptionId = string.Empty;

		public int amount;

		public int startTime;

		public int endTime;

		public string titleEn = string.Empty;

		public string titleRus = string.Empty;

		public string descriptionEn = string.Empty;

		public string descriptionRus = string.Empty;

		public string packsLeftEn = string.Empty;

		public string packsLeftRus = string.Empty;

		public bool isCashPromo = true;

		public int inAppPar = -1;

		public string showForNewOrOldUser = string.Empty;

		public string showForPayingOrNotUser = string.Empty;

		public int hoursFromStart;

		public int neededLeague;

		public bool isSingleUse;

		public string uniqueKey = string.Empty;

		public float inAppShowingPrice = -1f;

		public bool Enabled
		{
			get
			{
				bool flag = false;
				bool flag2 = false;
				bool flag3 = false;
				bool flag4 = PromoActionManager.NewUser(PromoActionManager.fyber.newUserStatusHours);
				if ((flag4 && showForNewOrOldUser == "new") || (!flag4 && showForNewOrOldUser == "old") || showForNewOrOldUser == string.Empty)
				{
					flag2 = true;
				}
				if ((PromoActionManager.PayingUser() && showForPayingOrNotUser == "payed") || (!PromoActionManager.PayingUser() && showForPayingOrNotUser == "non_payed") || showForPayingOrNotUser == string.Empty)
				{
					flag = true;
				}
				flag3 = PromoActionManager.PlayedHours(hoursFromStart);
				bool flag5 = enabled && gamerType == InAppShop.currentGamerType && !instance.currentId.Equals(subscriptionId) && PromoActionManager.CurrentUnixTimeSecond > startTime && PromoActionManager.CurrentUnixTimeSecond < endTime && (flag || flag2) && flag3 && neededLeague <= CupsManager.CurrentTier && (!isSingleUse || (isSingleUse && !BCWStorage.Get<bool>(uniqueKey)));
				if (flag5 && gamerType == GamerType.Hobo && hoboTime > 0 && PromoActionManager.PlayedHours(hoboTime))
				{
					flag5 = false;
				}
				return flag5;
			}
			set
			{
				enabled = value;
			}
		}

		public string GetTitle()
		{
			return (!(LocalizationManager.CurrentLanguage == "Russian")) ? titleEn : titleRus;
		}

		public string GetDescription()
		{
			return (!(LocalizationManager.CurrentLanguage == "Russian")) ? descriptionEn : descriptionRus;
		}

		public string GetPacksLeftTitle()
		{
			return GetPacksLeftTitle("ffff00ff");
		}

		public string GetPacksLeftTitle(string bbcode)
		{
			int packsLeftAmount = GetPacksLeftAmount();
			string arg = string.Format("[{0}]", bbcode) + packsLeftAmount + "[-]";
			return (!(LocalizationManager.CurrentLanguage == "Russian")) ? string.Format(packsLeftEn, arg) : string.Format(packsLeftRus, arg);
		}

		public int GetPacksLeftAmount()
		{
			int num = amount;
			int currentUnixTimeSecond = PromoActionManager.CurrentUnixTimeSecond;
			int num2 = startTime;
			int num3 = endTime;
			int num4 = Mathf.CeilToInt((1f - (float)(currentUnixTimeSecond - num2) / (float)(num3 - num2)) * (float)num);
			return (num4 <= 0) ? 1 : num4;
		}
	}

	[Serializable]
	public class SubscriptionParameters
	{
		public int maxDays;

		public int cycleHourse;

		public int startCash;

		public int startGold;

		public int cycleReward;
	}

	private const string KEY_SUBSCRIPTION_START_TIME = "subscriptionStartTime";

	private const string KEY_REWARD_START_TIME = "REWARDStartTime";

	private const string KEY_SUBSCRIPTION_ID = "subscriptionId";

	private static InAppSubscriptionsController _instance;

	public bool jsonReaded;

	private InAppPromo promo = new InAppPromo();

	private SubscriptionParameters currentSubscription = new SubscriptionParameters();

	private float timerJson;

	private float maxTimerJson = 10f;

	private string currentJson = "-1";

	private string newJson = "-1";

	private List<int> _andriodNotificationIds = new List<int>();

	public static InAppSubscriptionsController instance
	{
		get
		{
			if (_instance == null)
			{
				GameObject gameObject = new GameObject();
				gameObject.name = "InAppSubscriptionController(Don't Destroy)";
				gameObject.AddComponent<InAppPromoController>();
			}
			return _instance;
		}
	}

	public InAppPromo Promo
	{
		get
		{
			return promo;
		}
	}

	public SubscriptionParameters PromoParameters
	{
		get
		{
			return currentSubscription;
		}
	}

	public string currentId { get; private set; }

	public static event Action OnStartTimer;

	public static event Action OnStartSubscription;

	public static event Action OnEndSubscription;

	public static event Action OnJSONLoaded;

	public static event Action OnJSONParsed;

	private void Awake()
	{
		if (_instance != null)
		{
			UnityEngine.Object.DestroyImmediate(this);
			return;
		}
		_instance = this;
		UnityEngine.Object.DontDestroyOnLoad(base.gameObject);
	}

	private void Start()
	{
		currentId = BCWStorage.Get<string>("subscriptionId");
		StartCoroutine(RequestAndLoadSubscriptionJson());
		StartCoroutine(TimerForLoadJson());
	}

	private IEnumerator TimerForLoadJson()
	{
		while (true)
		{
			yield return new WaitForSeconds(1f);
			timerJson += 1f;
		}
	}

	public bool TryTakeReward()
	{
		if (GetCycleRemaininTime() <= 0)
		{
			if (GetSubscriptionRemaininDays() > 0)
			{
				StartTimer();
			}
			else
			{
				EndSubscription();
			}
			return true;
		}
		return false;
	}

	public bool GetSubscriptionState()
	{
		return !string.IsNullOrEmpty(currentId);
	}

	public int GetCycleRemaininTime()
	{
		return BCWStorage.Get<int>("REWARDStartTime") + currentSubscription.cycleHourse * 60 - JSONManager.Instance.GetServerTime();
	}

	public int GetSubscriptionRemaininDays()
	{
		return (BCWStorage.Get<int>("subscriptionStartTime") + currentSubscription.maxDays * 86400 - JSONManager.Instance.GetServerTime()) / 86400;
	}

	public void StartSubscription()
	{
		if (!string.IsNullOrEmpty(BCWStorage.Get<string>("subscriptionId")))
		{
			BCWDebug.LogError("LOG: Ваша старая подписка еще активна");
			return;
		}
		currentId = promo.subscriptionId;
		BCWStorage.Set("subscriptionId", promo.subscriptionId, true);
		BCWStorage.Set("subscriptionStartTime", JSONManager.Instance.GetServerTime(), true);
		if (InAppSubscriptionsController.OnStartSubscription != null)
		{
			InAppSubscriptionsController.OnStartSubscription();
		}
		StartTimer();
	}

	private void EndSubscription()
	{
		BCWStorage.Set("subscriptionId", string.Empty, true);
		BCWStorage.Set("subscriptionStartTime", 0, true);
		if (InAppSubscriptionsController.OnEndSubscription != null)
		{
			InAppSubscriptionsController.OnEndSubscription();
		}
	}

	private void StartTimer()
	{
		int serverTime = JSONManager.Instance.GetServerTime();
		BCWStorage.Set("REWARDStartTime", serverTime);
		if (InAppSubscriptionsController.OnStartTimer != null)
		{
			InAppSubscriptionsController.OnStartTimer();
		}
	}

	private IEnumerator RequestAndLoadSubscriptionJson()
	{
		while (!JSONManager.Instance.ServerTimeLoad())
		{
			yield return null;
		}
		yield return new WaitForSeconds(1.5f);
		string jsonText = JSONManager.Instance.GetJSON(URLs.InAppSubscriptions);
		string oldJson = string.Empty;
		while (jsonText == oldJson)
		{
			yield return new WaitForSeconds(3f);
			oldJson = jsonText;
			jsonText = JSONManager.Instance.GetJSON(URLs.InAppSubscriptions);
		}
		TryParseSubscriptionJson(jsonText);
		jsonReaded = true;
		if (InAppSubscriptionsController.OnJSONLoaded != null)
		{
			InAppSubscriptionsController.OnJSONLoaded();
		}
	}

	public void StartUpdateSubscriptionJson()
	{
		StartCoroutine(UpdateSubscriptionJson());
	}

	private IEnumerator UpdateSubscriptionJson()
	{
		if (timerJson < maxTimerJson)
		{
			yield break;
		}
		timerJson = 0f;
		if (!(SceneManager.GetActiveScene().name != "Lobby"))
		{
			newJson = JSONManager.Instance.GetJSON(URLs.InAppSubscriptions);
			if (currentJson != newJson)
			{
				TryParseSubscriptionJson(newJson);
				currentJson = newJson;
				BCWDebug.Log("Downloaded new subscription JSON.");
			}
			else
			{
				JSONManager.Instance.UpdateSignature(URLs.InAppSubscriptions);
				BCWDebug.Log("Subscription JSON didn't changed. Updating.");
			}
		}
	}

	private bool TryParseSubscriptionJson(string jsonText)
	{
		Dictionary<string, object> dictionary = Json.Deserialize(jsonText) as Dictionary<string, object>;
		if (dictionary == null)
		{
			return false;
		}
		if (dictionary.ContainsKey("promo"))
		{
			Dictionary<string, object> inAppPromoObj = dictionary["promo"] as Dictionary<string, object>;
			string key = ParsePromoObject(inAppPromoObj);
			ParseSubscription(dictionary[key] as Dictionary<string, object>);
			return true;
		}
		BCWDebug.Log("InApp Promo response doesn't contain “promos” property.", "Promo");
		return false;
	}

	private string ParsePromoObject(Dictionary<string, object> inAppPromoObj)
	{
		if (inAppPromoObj == null)
		{
			return string.Empty;
		}
		string str = string.Empty;
		new List<string>(inAppPromoObj.Keys).ForEach(delegate(string x)
		{
			str = str + x + "\n";
		});
		promo.Enabled = Convert.ToInt32(inAppPromoObj["enabled"]) == 1;
		promo.gamerType = (GamerType)Convert.ToInt32(inAppPromoObj["gamerType"]);
		promo.hoboTime = Convert.ToInt32(inAppPromoObj["hoboTime"]);
		promo.titleEn = (string)inAppPromoObj["titleEn"];
		promo.titleRus = (string)inAppPromoObj["titleRus"];
		promo.descriptionEn = (string)inAppPromoObj["descriptionEn"];
		promo.descriptionRus = (string)inAppPromoObj["descriptionRus"];
		promo.packsLeftEn = (string)inAppPromoObj["packsLeftEn"];
		promo.packsLeftRus = (string)inAppPromoObj["packsLeftRus"];
		promo.inAppPar = Convert.ToInt32((!inAppPromoObj.ContainsKey("inAppPar")) ? ((object)(-1)) : inAppPromoObj["inAppPar"]);
		promo.amount = Convert.ToInt32(inAppPromoObj["totalAmount"]);
		promo.startTime = Convert.ToInt32(inAppPromoObj["startTime"]);
		promo.endTime = Convert.ToInt32(inAppPromoObj["endTime"]);
		promo.showForNewOrOldUser = (string)((!inAppPromoObj.ContainsKey("newOldUser")) ? string.Empty : inAppPromoObj["newOldUser"]);
		promo.showForPayingOrNotUser = (string)((!inAppPromoObj.ContainsKey("payedNonPayedUser")) ? string.Empty : inAppPromoObj["payedNonPayedUser"]);
		promo.hoursFromStart = Convert.ToInt32((!inAppPromoObj.ContainsKey("hoursFromStart")) ? ((object)0) : inAppPromoObj["hoursFromStart"]);
		promo.neededLeague = Convert.ToInt32((!inAppPromoObj.ContainsKey("needLeague")) ? ((object)0) : inAppPromoObj["needLeague"]);
		promo.isSingleUse = inAppPromoObj.ContainsKey("singleUse") && Convert.ToInt32(inAppPromoObj["singleUse"]) == 1;
		promo.subscriptionId = (string)((!inAppPromoObj.ContainsKey("id")) ? string.Empty : inAppPromoObj["id"]);
		promo.uniqueKey = promo.startTime + promo.subscriptionId + promo.endTime;
		if (inAppPromoObj.ContainsKey("dollarPrice"))
		{
			string s = ((string)inAppPromoObj["dollarPrice"]).Replace(',', '.');
			float.TryParse(s, NumberStyles.Any, CultureInfo.InvariantCulture, out promo.inAppShowingPrice);
		}
		promo.isCashPromo = false;
		return promo.subscriptionId;
	}

	private void ParseSubscription(Dictionary<string, object> subscription)
	{
		if (subscription != null)
		{
			currentSubscription.maxDays = Convert.ToInt32((!subscription.ContainsKey("maxDays")) ? ((object)(-1)) : subscription["maxDays"]);
			currentSubscription.cycleHourse = Convert.ToInt32((!subscription.ContainsKey("cycleMinutes")) ? ((object)(-1)) : subscription["cycleMinutes"]);
			currentSubscription.startCash = Convert.ToInt32((!subscription.ContainsKey("startCash")) ? ((object)(-1)) : subscription["startCash"]);
			currentSubscription.startGold = Convert.ToInt32((!subscription.ContainsKey("startGold")) ? ((object)(-1)) : subscription["startGold"]);
			currentSubscription.cycleReward = Convert.ToInt32((!subscription.ContainsKey("cycleReward")) ? ((object)(-1)) : subscription["cycleReward"]);
			if (InAppSubscriptionsController.OnJSONParsed != null)
			{
				InAppSubscriptionsController.OnJSONParsed();
			}
		}
	}

	private void OnDestroy()
	{
		OnApplicationPause(true);
	}

	private void OnApplicationPause(bool onPause)
	{
		if (!onPause)
		{
			RemoveNotifications();
		}
		else if (JSONManager.Instance.ServerTimeLoad())
		{
			string title = ScriptLocalization.Get("Game_Common/money_notification_headline");
			string subtitle = ScriptLocalization.Get("Game_Common/money_notification_body");
			int cycleRemaininTime = GetCycleRemaininTime();
			if (cycleRemaininTime > 0)
			{
				AndroidNotificationConfiguration androidNotificationConfiguration = new AndroidNotificationConfiguration(cycleRemaininTime, title, subtitle, string.Empty);
				androidNotificationConfiguration.largeIcon = "large_icon";
				androidNotificationConfiguration.smallIcon = "small_icon";
				int item = EtceteraAndroid.scheduleNotification(androidNotificationConfiguration);
				_andriodNotificationIds.Add(item);
			}
		}
	}

	private void RemoveNotifications()
	{
		foreach (int andriodNotificationId in _andriodNotificationIds)
		{
			EtceteraAndroid.cancelNotification(andriodNotificationId);
		}
	}
}
